package com.web.dao.impl;

import com.entity.Customer;
import com.entity.CustomerExample;
import com.mapper.CustomerMapper;
import com.page.PageInfo;
import com.web.dao.CustomerDao;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Repository("customerDao")
public class CustomerDaoImpl implements CustomerDao {
    @Resource
    CustomerMapper customerMapper;

    public List<Customer> getAll() throws Exception {
        return customerMapper.getAll();
    }

    public  Customer selectByPrimaryKey(String cid) throws Exception {
        return customerMapper.selectByPrimaryKey(cid);
    }

    /**
     * 查询顾客关联的营养师
     * @param cid
     * @return
     * @throws Exception
     */
    public  Customer selectByPrimaryKeyWithDietian(String cid) throws Exception {
        return customerMapper.selectByPrimaryKeyWithDietian(cid);
    }

    /**
     * 查询顾客营养计划 具体执行 吃的食物
     * @param cid
     * @return
     * @throws Exception
     */
    public Customer selectByPrimaryKeyWithFood(String cid) throws Exception{
        return customerMapper.selectByPrimaryKeyWithFood(cid);
    }

    /**
     *
     * @param pageInfo
     * @return
     */
  public    List<Customer> getCustomersByPage(PageInfo pageInfo) throws Exception {
      Map<String,Object> map = new HashMap<String,Object>();
      map.put("currPage",pageInfo.getCurrPage());
      map.put("pageSize",pageInfo.getPageSize());

      int itemCount = (int)customerMapper.countByExample(null);
      pageInfo.setItemCount(itemCount);
      return customerMapper.getCustomersByPage(map);
  }



    public List<String> searchCustomerIdsByName(String petternName){
      /*示例example的用法*/
         CustomerExample customerExample = new CustomerExample();
         //查询姓王的会员
        //有两个集合  一个是 List<Criteria> oredCriteria; 控制条件与条件的关系     另外一个是 Criteria 保存的 List<Criterion> criteria;
//ce查询 理解1 createCriteria创建一个条件并加入到条件集合（如果是第一个条件 就加入条件集合）
                customerExample.createCriteria().andCnameLike("%"+petternName+"%"
        );
        customerExample.setDistinct(true);

//        Function<Customer,String> fn = new Function<Customer,String>() {
//            @Override
//            public String apply(Customer c) {
//                return c.getCid();
//            }
//        };
        return customerMapper.selectByExample(customerExample).stream().map(customer -> {return customer.getCid();}).collect(Collectors.toList());
    }


    public int add(Customer customer) throws Exception {
        return customerMapper.insertSelective(customer);
    }

    public int update(Customer customer) throws Exception {
        return customerMapper.updateByPrimaryKeySelective(customer);
    }

    public Customer getAccountByAccountName(String cname) throws Exception{
        return customerMapper.getAccountByAccountName(cname);
    }
}
